import sys
import asyncio
from quart import Quart
from src.common.utils.logger import log
from src.common.middleware.request_id import RequestIdMiddleware
from src.common.middleware.exception_handler import ExceptionHandler
from src.common.middleware.auth_middleware import AuthMiddleware
from src.common.container import container_manager, init_container, wire_modules, shutdown_container
from src.common.db.database import init_database, close_database
from src.common.utils.blueprint_loader import BlueprintLoader
from config.db_config import get_config

def create_app() -> Quart:
    """创建应用实例"""
    app = Quart(__name__)
    
    # =====应用配置====
    # 设置最大请求体大小为100MB，支持大文件上传
    app.config['MAX_CONTENT_LENGTH'] = 500 * 1024 * 1024  # 500MB
    
    # =====中间件注册====
    RequestIdMiddleware(app)
    AuthMiddleware(app)
    ExceptionHandler(app)
    
    return app

def setup_dependency_injection(app: Quart):
    """设置依赖注入"""
    try:
        # 获取配置
        config = get_config()
        
        # 初始化依赖注入容器
        init_container(config)
        
        # 装配需要依赖注入的模块 - 基础架构仅保留健康检查相关
        modules_to_wire = [
            # 基础架构暂不需要依赖注入的模块
            # 'src.route.healthy.healthy_route',
        ]
        
        wire_modules(modules_to_wire)
        log.info("依赖注入设置完成")
        
    except Exception as e:
        log.error(f"依赖注入设置失败: {str(e)}")
        raise

def setup_blueprints(app: Quart):
    """设置蓝图自动注册"""
    try:
        # 创建蓝图加载器
        blueprint_loader = BlueprintLoader(app)
        
        # 自动加载所有蓝图
        blueprints = blueprint_loader.load_blueprints("src/route")
        
        # 打印加载的蓝图信息
        blueprint_info = blueprint_loader.get_blueprint_info()
        for info in blueprint_info:
            log.info(f"已注册蓝图: {info['name']} -> {info['url_prefix']}")
            for route in info['routes']:
                log.debug(f"  路由: {route['methods']} {route['rule']} -> {route['endpoint']}")
        
        log.info(f"蓝图自动注册完成，共注册 {len(blueprints)} 个蓝图")
        
    except Exception as e:
        log.error(f"蓝图注册失败: {str(e)}")
        raise

# 创建应用实例
app = create_app()

@app.before_serving
async def startup():
    """应用启动时的初始化任务"""
    log.info("开始应用启动初始化...")
    
    try:
        # 初始化数据库连接
        await init_database()
        log.info("数据库连接初始化完成")
        
        # 设置依赖注入
        setup_dependency_injection(app)
        
        # 设置蓝图自动注册
        setup_blueprints(app)
        
        log.info("应用启动初始化完成")
        
    except Exception as e:
        log.error(f"应用启动初始化失败: {str(e)}")
        raise

@app.after_serving
async def cleanup():
    """应用关闭时的清理任务"""
    log.info("开始应用关闭清理...")
    
    try:
        # 关闭依赖注入容器
        shutdown_container()
        log.info("依赖注入容器已关闭")
        
        # 关闭数据库连接
        await close_database()
        log.info("数据库连接已关闭")
        
        log.info("应用关闭清理完成")
        
    except Exception as e:
        log.error(f"应用关闭清理失败: {str(e)}")

if __name__ == '__main__':
    port = int(sys.argv[1]) if len(sys.argv) > 1 else 5001
    app.run(host='0.0.0.0', port=port, debug=False)